package com.i8office.android.zhihuixinwu.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseActivity;
import com.cyan.tools.util.RxBus;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.adapter.AttachmentAdapter;
import com.i8office.android.zhihuixinwu.bean.Empl;
import com.i8office.android.zhihuixinwu.bean.Favorite;
import com.i8office.android.zhihuixinwu.bean.NotifyTarget;
import com.i8office.android.zhihuixinwu.bean.SendTarget;
import com.i8office.android.zhihuixinwu.bean.WorkSheet;
import com.i8office.android.zhihuixinwu.bean.WorkSheetNew;
import com.i8office.android.zhihuixinwu.config.Constants;
import com.i8office.android.zhihuixinwu.module.contract.DetailContract;
import com.i8office.android.zhihuixinwu.module.presenter.DetailPresenter;
import com.i8office.android.zhihuixinwu.ui.dep.OfficeNewActivity;
import com.i8office.android.zhihuixinwu.util.ToastUtils;
import com.i8office.android.zhihuixinwu.widget.ItemDecoration;
import com.socks.library.KLog;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.Main;
import bean.WorkFlow;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tools.ToastUtil;
import view.ThreePointLoadingView;

@ActivityFragmentInject(
        contentViewId = R.layout.activity_detail
)
public class DetailActivity extends BaseActivity<DetailContract.Presenter> implements DetailContract.View, DetailFragment.OnGetPageTitle {
    public static String from = "office";
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.read)
    TextView read;
    @BindView(R.id.modify)
    TextView modify;
    @BindView(R.id.collect)
    TextView mCollect;
    @BindView(R.id.sign)
    TextView sign;
    @BindView(R.id.loading)
    ThreePointLoadingView loading;
    private ActionBarDrawerToggle mDrawerToggle;
    AttachmentAdapter adapter;
    WorkFlow workFlow;
    WorkSheet workSheet;
    List<Fragment> fragments = new ArrayList<>();
    Empl empl;
    boolean mIsFavorite = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        from = getIntent().getStringExtra("from");
        /*mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
        mDrawerToggle.syncState();
        drawerLayout.addDrawerListener(mDrawerToggle);*/
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        adapter = new AttachmentAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new ItemDecoration(this, 1));
        recyclerView.setAdapter(adapter);
        mPresenter = new DetailPresenter(this);
        workFlow = getIntent().getParcelableExtra("workFlow");
        mPresenter.getDetail(workFlow.getMessageId());
        mPresenter.isFavorite(workFlow.getMessageId());
    }

    @OnClick({R.id.index, R.id.read, R.id.sign, R.id.modify, R.id.collect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.index:
                drawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.read:
                read.setEnabled(false);
                Map<String, String> params = new HashMap<>();
                params.put("sid", workSheet.getSid());
                params.put("nid", workSheet.getNid());
                params.put("row", workSheet.getControl().getShowReadedButton().getRow());
                params.put("col", workSheet.getControl().getShowReadedButton().getCol());
                params.put("val", "已阅");
                params.put("ival", "");
                mPresenter.saveCell(params);
                break;
            case R.id.sign:
                if (workSheet == null) {
                    return;
                }
                if (workSheet.getControl().getNeedOpinion().isShow()) {
                    startActivity(new Intent(this, SuggestionActivity.class).putExtra("workSheet", workSheet));
                } else {
                    startActivity(getIntent().setClass(this, StaffActivity.class).putExtra("workSheet", workSheet).putExtra("memo", ""));
                }

                break;
            case R.id.modify://修改
                startActivity(new Intent(this, ModifySuggestionActivity.class).putExtra("workSheet", workSheet));
                break;
            case R.id.collect:
                if (mIsFavorite) {
                    mPresenter.cancelFavorite(workSheet.getMid());
                } else {
                    mPresenter.addFavorite(workSheet.getMid());
                }
                break;
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                if (this.getClass() != MainActivity.class)
                if (drawerLayout.isDrawerOpen(Gravity.START)) {
                    drawerLayout.closeDrawers();
                } else {
                    if (from.equals("main")) {
                        Intent intent = new Intent(this, Main.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                    finish();
                }
                return true;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if(resultCode==RESULT_OK){
//            setResult(RESULT_OK);
//            finish();
//        }
//    }

    @Override
    public void showDetail(final WorkSheet workSheet) {
        this.workSheet = workSheet;
        List<WorkSheet.AttachmentsBean> attachmentsBeans = new ArrayList<>();
        WorkSheet.AttachmentsBean first = new WorkSheet.AttachmentsBean(workSheet.getDocumentTitleName(), 1);
        attachmentsBeans.add(first);
        attachmentsBeans.addAll(workSheet.getAttachments());
        this.workSheet.getAllAttachments().add(first);
        this.workSheet.getAllAttachments().addAll(workSheet.getAttachments());
        if (workSheet.getDetpAttachments() != null && workSheet.getDetpAttachments().size() > 0) {
            attachmentsBeans.add(new WorkSheet.AttachmentsBean("部门承办意见附件", 1));
            attachmentsBeans.addAll(workSheet.getDetpAttachments());
            workSheet.getAllAttachments().addAll(workSheet.getDetpAttachments());
        }
        adapter.addAll(attachmentsBeans);
        adapter.setOnItemClick(new AttachmentAdapter.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                viewpager.setCurrentItem(position > workSheet.getAttachments().size() + 1 ? position - 1 : position);
                drawerLayout.closeDrawers();
            }
        });
        viewpager.setOffscreenPageLimit(0);
        for (int i = 0; i < workSheet.getAllAttachments().size(); i++) {
            Fragment fragment = null;
            Bundle bundle = new Bundle();
            switch (i) {
                case 0:
                    fragment = new DetailFragment();
                    String url = Constants.BASE_URL+"/Apps/Tiger/Workflow/GetDetailPage?mid="+workFlow.getMessageId();
                    bundle.putString("url", url);
                    fragment.setArguments(bundle);
                    break;
                default:
                    fragment = new AttachmentFragment();
                    bundle.putString("id", workSheet.getAllAttachments().get(i).getAttId());
                    bundle.putString("fileName", workSheet.getAllAttachments().get(i).getAttFileName());
                    fragment.setArguments(bundle);
//                    fragment = new PDFShowFragment();
                    break;
            }
            fragments.add(fragment);
        }

        viewpager.setAdapter(new MyPageAdapter(getSupportFragmentManager()));
        if (workSheet.getControl() == null) {
            sign.setVisibility(View.GONE);
//            cancel.setVisibility(View.GONE);
            read.setVisibility(View.GONE);
        } else {
            sign.setVisibility(View.VISIBLE);
//            cancel.setVisibility(View.VISIBLE);
            if (workSheet.getControl().getShowReadedButton().isShow())
                read.setVisibility(View.VISIBLE);
        }
        modify.setVisibility(workSheet.getModify().isShow() ? View.VISIBLE : View.GONE);
        if (workSheet.getModify().isShow()) {
            sign.setVisibility(View.GONE);
        }
    }

    @Override
    public void showDetailDep(WorkSheetNew workSheet) {

    }

    @Override
    public void showFavorite(Favorite favorite) {
        mIsFavorite = favorite.isFavorite;
        mCollect.setText(mIsFavorite ? R.string.collected : R.string.collect);
        mCollect.setSelected(mIsFavorite);
        mCollect.setVisibility(View.VISIBLE);
    }


    /**
     * Created by jiajia on 2018/3/15.
     */
    public class MyPageAdapter extends FragmentStatePagerAdapter {
        private FragmentManager mFManager;

        public MyPageAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
            mFManager = fragmentManager;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = (Fragment) super.instantiateItem(container, position);
            this.mFManager.beginTransaction().show(fragment).commit();
            return fragment;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            Fragment fragment = fragments.get(position);
            mFManager.beginTransaction().hide(fragment).commit();
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }


        @Override
        public int getCount() {
            return fragments == null ? 0 : fragments.size();
        }
    }

    @Override
    public void saveCellSuccess() {
        Map<String, String> params = new HashMap<>();
        params.put("MessageID", workSheet.getMid());
        params.put("FromNodeKey", workSheet.getNid());
        params.put("NodeKey", workSheet.getControl().getShowReadedButton().getTargetNodeKey());
        mPresenter.messageHandler(params);
    }

    @Override
    public void messageHandlerResult(Empl empl) {
        this.empl = empl;
        Map<String, String> params = new HashMap<>();
        params.put("memo", "");
        params.put("memoAtts", "[]");
        params.put("mid", workSheet.getMid());
        params.put("nid", workSheet.getNid());
        List<SendTarget> targets = new ArrayList<>();
        targets.add(new SendTarget(workSheet.getControl().getShowReadedButton().getTargetNodeKey(), empl.empl, "multi"));
        params.put("targets", new Gson().toJson(targets));
        mPresenter.send(params);
    }

    @Override
    public void sendSuccess() {
        RxBus.get().post("submitSuccess", "");
        ToastUtil.showCenter(this, R.string.submit_success);
        if (from.equals("office")) {
            Intent intent = new Intent(this, OfficeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }else if(from.equals("office_new")){
            Intent intent = new Intent(this, OfficeNewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (from.equals("main")) {
            Intent intent = new Intent(this, Main.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        from = "";

//        Map<String, String> params = new HashMap<>();
//        params.put("mid", workSheet.getMid());
//        params.put("sendsucc", "1");
//        mPresenter.open(params);


        //已阅提交成功之后发送通知
        Map<String, String> params1 = new HashMap<>();
        params1.put("mid", workSheet.getMid());
        params1.put("nodekey", workSheet.getNid());
        List<NotifyTarget> targets = new ArrayList<>();
        targets.add(new NotifyTarget(workSheet.getControl().getShowReadedButton().getTargetNodeKey(), empl == null ? "" : empl.empl));
        String nlist = new Gson().toJson(targets);
        params1.put("nlist", nlist);
        KLog.e("target==" + new Gson().toJson(params1));
        mPresenter.sendNotification(params1);
    }

    @Override
    public void onfailed() {
        read.setEnabled(true);
    }

//    @Override
//    public void openResult() {
//
//    }

    @Override
    public void collectResult(boolean b) {
        mIsFavorite = b;
        mCollect.setSelected(mIsFavorite);
        mCollect.setText(mIsFavorite ? R.string.collected : R.string.collect);
        ToastUtils.showCollectToast(this, b ? R.string.collect_success : R.string.collect_cancel);
        RxBus.get().post("collect","");
    }


    @Override
    public void showProgress() {
        loading.play();
    }

    @Override
    public void hideProgress() {
        loading.stop();
    }

    @Override
    public void onGetPageTitle(String title) {
        TextView tvTitle = (TextView) findViewById(com.cyan.tools.R.id.title);
        if (tvTitle != null) {
            tvTitle.setText(title);
        }
    }
}
